Java - tutorial - 10/13 - class methods

revision:


Java - class methods

Methods are declared within a class and are used to perform certain actions.

Methods are called: to call a method, write the method's name followed by two parentheses () and a semicolon(;).

example:

          public class Main {
              static void myMethod() {
                System.out.println("Hello World!");
              }
              public static void main(String[] args) {
                myMethod();
              }
          }
          // Outputs "Hello World!"
      

static vs. non-static: Java programs have either static or public attributes and methods. A "static" method can be accessed without creating an object of the class, unlike a "public" method, which can only be accessed by objects.

example:

        public class Main {
            // Static method
            static void myStaticMethod() {
              System.out.println("Static methods can be called without creating objects");
            }
            // Public method
            public void myPublicMethod() {
              System.out.println("Public methods must be called by creating objects");
            }
            // Main method
            public static void main(String[] args) {
              myStaticMethod(); // Call the static method
              // myPublicMethod(); This would compile an error
              Main myObj = new Main(); // Create an object of Main
              myObj.myPublicMethod(); // Call the public method on the object
            }
          }
    

access methods with an object: the dot (.) is used to access the object's attributes and methods. To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon (;).


Java - constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

the constructor name must match the class name, and it cannot have a return type (like void).
the constructor is called when the object is created.
all classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

example:

        // Create a Main class
        public class Main {
        int x;  // Create a class attribute
        // Create a class constructor for the Main class
        public Main() {
            x = 5;  // Set the initial value for the class attribute x
        }
        public static void main(String[] args) {
            Main myObj = new Main(); // Create an object of class Main --> call the constructor
            System.out.println(myObj.x); // Print the value of x
        }
        }
        // Outputs 5
   

Constructors can also take parameters, which is used to initialize attributes. You can have as many parameters as you want:

example:

        public class Main {
            int modelYear;
            String modelName;
            public Main(int year, String name) {
            modelYear = year;
            modelName = name;
            }
            public static void main(String[] args) {
            Main myCar = new Main(1969, "Mustang");
            System.out.println(myCar.modelYear + " " + myCar.modelName);
            }
        }
        // Outputs 1969 Mustang
   

Java - modifiers

The public keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods and constructors. Modifiers are divided into two groups:

access modifiers, which control the access level;
non-access modifiers, which do not control access level, but provides other functionalit;y

access modifiers:

For classes, you can use either "public" or "default":

"public": the class is accessible by any other class.
"default": the class is only accessible by classes in the same package. This is used when you don't specify a modifier.

For attributes, methods, and constructors, you can use one of the follwing:

"public": the code is accessible for all classes.
"private": the code is only accessible within the declared class .
"default": the code is only accessible in the same package. This is used when you don't specify a modifier.
"protected": the code is accessible in the same package and subclasses.

non-access modifiers

For classes, you can use either final or abstract:

"final": the class cannot be inherited by other classes.
"abstract": the class cannot be used to create objects (to access an abstract class, it must be inherited from another class).

For attributes and methods, you can use one of the follwing:

"final": attributes and methods cannot be overridden/modified.
"static": attributes and methods belong to the class, rather than an object.
"abstract": can only be used in an abstract class, and can only be used on methods. The method does not have a body, for example abstract void run();. The body is provided by the subclass (inherited from).
"transient": attributes and methods are skipped when serializing the object containing them.
"synchronized": methods can only be accessed by one thread at a time.
"volatile": the value of an attribute is not cached thread-locally, and is always read from the "main memory".

If you don't want the ability to override existing attribute values, declare attributes as final.

example:

    public class Main {
        final int x = 10;
        final double PI = 3.14;
        public static void main(String[] args) {
          Main myObj = new Main();
          myObj.x = 50; // will generate an error: cannot assign a value to a final variable
          myObj.PI = 25; // will generate an error: cannot assign a value to a final variable
          System.out.println(myObj.x);
        }
    }
   

A static method means that it can be accessed without creating an object of the class, unlike "public".

An abstract method belongs to an abstract class, and it does not have a body. The body is provided by the subclass.


Java - encapsulation

The meaning of encapsulation is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private and provide public get and set methods to access and update the value of a private variable

private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods.

The "get method" returns the variable value, and the "set method" sets the value.
"Syntax for both" is that they start with either "get" or "set", followed by the name of the variable, with the first letter in upper case.

example:

        public class Person {
            private String name; // private = restricted access
            // Getter
            public String getName() {
              return name;
            }
            // Setter
            public void setName(String newName) {
              this.name = newName;
            }
          }
    

Encapsulation provides better control of class attributes and methods, as class attributes can be made read-only (if you only use the get method), or write-only (if you only use the set method). It offers more flexibility, as the programmer can change one part of the code without affecting other parts. Lastly, it increases data security.